package com.example.myapplication

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import kotlinx.coroutines.launch
import androidx.compose.foundation.background
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Settings
import androidx.compose.ui.platform.LocalContext

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainAppShell(
    navController: NavController,
    content: @Composable () -> Unit
) {
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val context = LocalContext.current
    // 抽屉内容区域宽度：75% 屏幕宽，最大 400.dp
    val drawerContentWidth = (screenWidth * 0.75f).coerceAtMost(400.dp)

    ModalNavigationDrawer(
        drawerState = drawerState,
        // ✅ 关键：用 scrimColor 控制遮罩透明度
        scrimColor = Color.Black.copy(alpha = 0.3f),
        drawerContent = {
            // 整个 drawer 是全屏的，但我们只在右侧渲染一个“窄面板”
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Transparent) // 抽屉背景透明，靠内层 Surface 控制
            ) {
                // 将内容靠左对齐（LTR），并限制宽度
                Surface(
                    shape = RoundedCornerShape(topEnd = 12.dp, bottomEnd = 12.dp),
                    color = MaterialTheme.colorScheme.surface, // 白色（浅色主题）
                    shadowElevation = 4.dp,
                    modifier = Modifier
                        .width(drawerContentWidth)
                        .fillMaxHeight()
                        .align(Alignment.TopStart) // 从左侧开始
                ) {
                    Column(
                        modifier = Modifier
                            .padding(16.dp)
                            .fillMaxHeight()
                            .verticalScroll(rememberScrollState())
                    ) {
                        Spacer(Modifier.height(60.dp))
                        Text(
                            modifier = Modifier.align(Alignment.CenterHorizontally),
                            text = "Hi, ${AccountManager.ActiveAccount ?: "Guest"}",
                            fontWeight = FontWeight.Bold,
                            style = MaterialTheme.typography.titleMedium
                        )
                        Spacer(Modifier.height(16.dp))
                        NavigationItem(
                            text = "主页",
                            icon = Icons.Default.Home,
                            onClick = {
                                scope.launch {
                                    drawerState.close()
                                    navController.navigate("main") {
                                        popUpTo(navController.graph.startDestinationId) {
                                            inclusive = true
                                        }
                                    }
                                }
                            }
                        )
                        NavigationItem(
                            text = "设置",
                            icon = Icons.Default.Settings,
                            onClick = {
                                scope.launch {
                                    drawerState.close()
                                    navController.navigate("config") {
                                        popUpTo(navController.graph.startDestinationId) {
                                            inclusive = true
                                        }
                                    }
                                }
                            }
                        )
                        NavigationItem(
                            text = "退出登录",
                            icon = Icons.Default.ExitToApp,
                            onClick = {
                                AccountManager.logout(context);
                                scope.launch {
                                    drawerState.close()
                                    navController.navigate("login") {
                                        popUpTo(navController.graph.startDestinationId) {
                                            inclusive = true
                                        }
                                    }
                                }
                            }
                        )
                        // 可继续添加项
                    }
                }
            }
        }
    ) {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("TestApp") },
                    navigationIcon = {
                        IconButton(onClick = { scope.launch { drawerState.open() } }) {
                            Icon(Icons.Default.Menu, contentDescription = "菜单")
                        }
                    }
                )
            }
        ) { padding ->
            Box(Modifier.padding(padding)) {
                content()
            }
        }
    }
}

@Composable
private fun NavigationItem(
    text: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    onClick: () -> Unit
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.size(24.dp)
        )
        Spacer(Modifier.width(12.dp))
        Text(
            text = text,
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurface
        )
    }
}